package edu.sdbi.judge.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import edu.sdbi.judge.domain.entity.Visit;
import edu.sdbi.judge.mapper.CommentMapper;
import edu.sdbi.judge.mapper.NewsMapper;
import edu.sdbi.judge.mapper.UserMapper;
import edu.sdbi.judge.mapper.VisitMapper;
import edu.sdbi.judge.service.DatainitializeService;
import lombok.var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class DatainitializeServiceImpl implements DatainitializeService {
    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private NewsMapper NewsMapper;
    @Autowired
    private VisitMapper visitMapper;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private UserMapper userMapper;

    @Override
    public void init() {
//        commentMapper.delete();
//        visitMapper.delete();
//        NewsMapper.delete();
//        userMapper.delete();


        //Comment表的数据初始化
        try {
            List<String> comments = readSqlFromConfig();
            jdbcTemplate.batchUpdate(comments.toArray(new String[0]));
        } catch (IOException e) {
            throw new RuntimeException("初始化数据失败", e);
        }
    }

    // 从配置文件读取news表中的数据
    private List<String> readnewsFromConfig() throws IOException {
        try (InputStream is = new ClassPathResource("init-data/news.json").getInputStream();
             BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) {

            // 读取整个 JSON 文件为字符串
            StringBuilder content = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                content.append(line);
            }
            String jsonContent = content.toString();

            // 解析 JSON 数组，将每个元素转换为字符串
            JsonNode rootNode = objectMapper.readTree(jsonContent);
            List<String> newsJsonList = new ArrayList<>();

            for (JsonNode newsNode : rootNode) {
                newsJsonList.add(objectMapper.writeValueAsString(newsNode));
            }

            return newsJsonList;
        }
    }

    private String buildcommentInsertSql(List<String> newsJsonList) {
        if (newsJsonList == null || newsJsonList.isEmpty()) {
            return "";
        }
        StringBuilder sql = new StringBuilder();
        sql.append("INSERT INTO comment (id, type, relation_id, text, create_user_id, create_time, is_delete) VALUES ");

        for (int i = 0; i < newsJsonList.size(); i++) {
            try {
                JsonNode commentNode = objectMapper.readTree(newsJsonList.get(i));
                // 提取 JSON 中的字段值
                String id = commentNode.get("id").asText();
                String type = commentNode.get("type").asText();
                String relationId = commentNode.get("relationId").asText();
                String text = commentNode.get("text").asText();
                String createUserId = commentNode.get("createUserId").asText();
                String createTime = commentNode.get("createTime").asText();
                String isDelete = commentNode.get("isDelete").asText();
                // 对于 null 或缺失字段，都返回默认值
                // 拼接 VALUES 子句（使用 MyBatis 参数占位符）
                sql.append("(#{" + id + "},")
                        .append("(#{" + type + "},")
                        .append("(#{" + relationId + "},")
                        .append("(#{" + text + "},")
                        .append("(#{" + createUserId + "},")
                        .append("(#{" + createTime + "},")
                        .append("(#{" + isDelete + "},)");

                if (i < newsJsonList.size() - 1) {
                    sql.append(",");
                }
            } catch (JsonProcessingException e) {
                throw new RuntimeException("解析评论 JSON 失败", e);
            }
        }
        System.out.println(sql.toString() + "456465465465465465465465");
        return sql.toString();
    }

    // 从配置文件读取visit表数据
    private List<Visit> readvisitFromConfig() throws IOException {
        try (var is = new ClassPathResource("init-data/visit.json").getInputStream()) {
            Visit[] visit = objectMapper.readValue(is, Visit[].class);
            return Arrays.asList(visit);
        }
    }

    // 从配置文件读取Comment表的数据
    private List<String> readSqlFromConfig() throws IOException {
        List<String> sqlList = new ArrayList<>();
        try (InputStream is = new ClassPathResource("init-data/init.sql").getInputStream();
             BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) {

            // 读取SQL文件为字符串
            String line;
            while ((line = reader.readLine()) != null) {
                if (!line.isEmpty()) {
                    sqlList.add(line);
                }
            }
        }
        return sqlList;
    }

}
